﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraSplashScreen;
using ISumen;
using Sumen.Business;
using Sumen.Business.Model;
using Sumen.Business.Model.Presenter.Actor;
using Sumen.Business.Model.Presenter.Category;
using Sumen.Business.Model.Presenter.Inventory;
using Sumen.Business.Model.Presenter.Sales;
using Sumen.Business.Model.Presenter.Sys;
using Sumen_Stock.LookAndFeel.Sumen_System;

namespace Sumen_Stock.LookAndFeel.Sales
{
    public partial class Frm_Split_Orders : DevExpress.XtraEditors.XtraForm
    {

        #region Variable

        private InventoryPresenter _inventoryPresenter;
        private OrderStatusPresenter _orderStatusPresenter;
        private CustomerTypePresenter _customerTypePresenter;
        private CustomerPresenter _customerPresenter;
        private OrdersPresenter _ordersPresenter;
        private customer _cus;
        order Order
        {
            get;
            set;
        }

        List<tempOrderDetails> TempOrderDetailses
        {
            get;
            set;
        }

        public bool IsSuccess
        {
            get;
            set;
        }

        #endregion


        #region From

        public Frm_Split_Orders(order pOrder)
        {
            InitializeComponent();
            Order = pOrder;
            _inventoryPresenter = new InventoryPresenter();
            _orderStatusPresenter = new OrderStatusPresenter();
            _customerTypePresenter = new CustomerTypePresenter();
            _customerPresenter = new CustomerPresenter();
            _ordersPresenter = new OrdersPresenter();
        }

        private void Frm_Split_Orders_Load(object sender, EventArgs e)
        {
            LoadForm();
        }

        public override void Refresh()
        {
            base.Refresh();
        }

        #endregion


        #region Button event

        private void buttonsArray1_btnEventAdd_click(object sender, EventArgs e)
        {
            if (Validation())
            {
                List<orders_details> listOrdersDetailsOutOfStock = new List<orders_details>();
                //thanh toan hoa don
                Order.orders_details.Clear();
                Order.Ord_Deposit = 0;
                Order.Ord_Cash = Convert.ToDecimal(txtSummary.EditValue);
                Order.Ord_Change = Convert.ToDecimal(txtCharge.EditValue);
                foreach (var tempOrderDetailse in TempOrderDetailses)
                {
                    Order.orders_details.Add(tempOrderDetailse.OrdersDetails);
                    //orders hàng tạm hết
                    orders_details ordersDetailsOutOfStock = new orders_details();
                    ordersDetailsOutOfStock.Ords_CatId = tempOrderDetailse.OrdersDetails.Ords_CatId;
                    ordersDetailsOutOfStock.Ords_Description = tempOrderDetailse.OrdersDetails.Ords_Description;
                    ordersDetailsOutOfStock.Ords_Discount = tempOrderDetailse.OrdersDetails.Ords_Discount;
                    ordersDetailsOutOfStock.Ords_DiscountRate = tempOrderDetailse.OrdersDetails.Ords_DiscountRate;
                    ordersDetailsOutOfStock.Ords_IsOrders = tempOrderDetailse.OrdersDetails.Ords_IsOrders;
                    ordersDetailsOutOfStock.Ords_IsOrders_Image = tempOrderDetailse.OrdersDetails.Ords_IsOrders_Image;
                    ordersDetailsOutOfStock.Ords_IsReturned = tempOrderDetailse.OrdersDetails.Ords_IsReturned;
                    ordersDetailsOutOfStock.Ords_PRODUCT_DETAILS_ID = tempOrderDetailse.OrdersDetails.Ords_PRODUCT_DETAILS_ID;
                    ordersDetailsOutOfStock.Ords_Picture = tempOrderDetailse.OrdersDetails.Ords_Picture;
                    ordersDetailsOutOfStock.Ords_Product_Name = tempOrderDetailse.OrdersDetails.Ords_Product_Name;
                    ordersDetailsOutOfStock.Ords_Surcharge = tempOrderDetailse.OrdersDetails.Ords_Surcharge;
                    ordersDetailsOutOfStock.Ords_UnitPrice = tempOrderDetailse.OrdersDetails.Ords_UnitPrice;
                    ordersDetailsOutOfStock.Ords_Quantity = tempOrderDetailse.QuantityAdd;
                    listOrdersDetailsOutOfStock.Add(ordersDetailsOutOfStock);
                }
                _ordersPresenter.Add(Order);
                ClsPublic.WriteLog(FromCode.FrmSale, EnumFormStatus.Add, Order.Ord_Code, "");

                // tao orders hàng tạm hết
                order orderOutOfStock = new order();
                orderOutOfStock.Ord_Payment_Status = (int)OrdersStatus.OrderOutOfStock;
                orderOutOfStock.Ord_Code = _ordersPresenter.GetNewCodeOrders(Order.Ord_Date_Orders);
                orderOutOfStock.Ord_Sorted = long.Parse(orderOutOfStock.Ord_Code.Split('-')[2]);
                orderOutOfStock.Ord_Cash = 0;
                orderOutOfStock.Ord_Change = 0;
                orderOutOfStock.Ord_Customer_Address = Order.Ord_Customer_Address;
                orderOutOfStock.Ord_Customer_Contact = Order.Ord_Customer_Contact;
                orderOutOfStock.Ord_Customer_ID = Order.Ord_Customer_ID;
                orderOutOfStock.Ord_Customer_Name = Order.Ord_Customer_Name;
                orderOutOfStock.Ord_DISTRICT_ID = Order.Ord_DISTRICT_ID;
                orderOutOfStock.Ord_Date_Orders = Order.Ord_Date_Orders;
                orderOutOfStock.Ord_Deposit = Convert.ToDecimal(txtDeposit.EditValue);
                orderOutOfStock.Ord_Description = Order.Ord_Description;
                orderOutOfStock.Ord_Discount = Order.Ord_Discount;
                orderOutOfStock.Ord_DiscountRate = Order.Ord_DiscountRate;
                orderOutOfStock.Ord_IsOrder = Order.Ord_IsOrder;
                //orderOutOfStock.Ord_Total_Amount = Order.Ord_Total_Amount;
                orderOutOfStock.Ord_User_ID = Order.Ord_User_ID;
                orderOutOfStock.Ord_VAT = Order.Ord_VAT;
                orderOutOfStock.orders_details = listOrdersDetailsOutOfStock;
                _ordersPresenter.Add(orderOutOfStock);
                ClsPublic.WriteLog(FromCode.FrmSale, EnumFormStatus.Add, orderOutOfStock.Ord_Code, "");

                //hiển thị bảng in hóa đơn đã thanh toán
                SplashScreenManager.ShowForm(typeof(WaitForm1));
                Frm_Confirm_Sales frmConfirm = new Frm_Confirm_Sales(Order, _cus);
                frmConfirm.FormStatus = EnumFormStatus.Print;
                frmConfirm.Closed += frmConfirm_Closed;
                SplashScreenManager.CloseForm();
                frmConfirm.ShowDialog();

            }
        }

        void frmConfirm_Closed(object sender, EventArgs e)
        {
            IsSuccess = true;
            this.Close();
        }

        private void buttonsArray1_btnEventClose_click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtCash_EditValueChanged(object sender, EventArgs e)
        {
            Order.Ord_Cash = Convert.ToDecimal(txtCash.EditValue);
            SetCharge();
        }

        #endregion


        #region Grid event

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            SetCharge();

        }

        private void resCalcQuantity_EditValueChanged(object sender, EventArgs e)
        {
            // SetCharge();
        }

        private void resCalcQuantityAdd_EditValueChanged(object sender, EventArgs e)
        {
            // SetCharge();
        }

        private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            int iRow = gridView1.FocusedRowHandle;


            int sQuantityStock = Convert.ToInt32(gridView1.GetRowCellValue(iRow, colQuanityStock));
            int sQuantity = Convert.ToInt32(gridView1.GetRowCellValue(iRow, colQuantity));
            int sQuantityAdd = Convert.ToInt32(gridView1.GetRowCellValue(iRow, colQuantityAdd));

            ////////////////////////////////////////////////////////////////////////////
            if (sQuantity == 0)
            {
                gridView1.SetColumnError(colQuantity, string.Format("Bạn chưa nhập số lượng sản phẩm mua."));
                e.Valid = false;
            }
            ////////////////////////////////////////////////////////////////////////////
            if (sQuantityAdd == 0)
            {
                gridView1.SetColumnError(colQuantityAdd, string.Format("Bạn chưa nhập số lượng sản phẩm mua thêm."));
                e.Valid = false;
            }
            ////////////////////////////////////////////////////////////////////////////
            if (sQuantityStock < sQuantity)
            {
                gridView1.SetColumnError(colQuantity, string.Format("Không đủ số lượng trong kho."));
                e.Valid = false;
            }
        }

        #endregion





        #region Methoad load from

        void LoadForm()
        {
            LoadStatus();
            LoadCustomerType();
            LoadGrid();
            LoadOrdersInfo();
        }

        void LoadGrid()
        {
            TempOrderDetailses = new List<tempOrderDetails>();
            foreach (var ordersDetailse in Order.orders_details)
            {
                //Convert.to
                tempOrderDetails obj = new tempOrderDetails();
                //obj =(tempOrderDetails) ordersDetailse;
                obj.OrdersDetails = ordersDetailse;
                //obj = (tempOrderDetails)ordersDetailse;
                obj.QuantityStock = _inventoryPresenter.GetQuantityByProductDetailsId(obj.OrdersDetails.Ords_PRODUCT_DETAILS_ID);
                if (obj.QuantityStock < obj.OrdersDetails.Ords_Quantity)
                {
                    obj.QuantityAdd = (int)(obj.OrdersDetails.Ords_Quantity - obj.QuantityStock);
                    obj.OrdersDetails.Ords_Quantity = obj.QuantityStock;
                }
                else
                {
                    obj.QuantityAdd = 0;
                }

                TempOrderDetailses.Add(obj);
            }
            var result = new BindingSource(TempOrderDetailses, "");
            gridControl1.DataSource = result;
            SetCharge();
        }

        void LoadOrdersInfo()
        {
            //load order info
            txtOrdersCode.EditValue = Order.Ord_Code;
            lookUpStatus.EditValue = Order.Ord_Payment_Status;
            txtDate.EditValue = Order.Ord_Date_Orders;
            txtUser.EditValue = Order.Ord_User_ID;
            txtDesc.EditValue = Order.Ord_Description;

            //load cus info
            txtCusUserName.EditValue = Order.Ord_Customer_ID;
            txtCusName.EditValue = Order.Ord_Customer_Name;
            txtCusPhone.EditValue = Order.Ord_Customer_Contact;
            _cus = _customerPresenter.GetById(Order.Ord_Customer_ID);
            lookUpOrderCusType.EditValue = _cus.Cus_CUSTOMER_TYPE_ID;
            txtCusAddress.EditValue = Order.Ord_Customer_Address;
            spinDiscount.EditValue = Order.Ord_DiscountRate;
            txtDeposit.EditValue = Order.Ord_Deposit;

        }

        void LoadStatus()
        {
            lookUpStatus.Properties.DataSource = _orderStatusPresenter.GetListOrderStatus();
        }

        void LoadCustomerType()
        {
            lookUpOrderCusType.Properties.DataSource = _customerTypePresenter.GetAll();

        }

        void SetCharge()
        {
            txtSummary.EditValue = Order.Ord_Total_Amount + Order.Ord_Deposit * 2;
            txtCharge.EditValue = Order.Ord_Cash - (Order.Ord_Total_Amount + Order.Ord_Deposit * 2);
            gridView1.RefreshData();
            if (gridView1.UpdateCurrentRow())
            {
                gridView1.UpdateTotalSummary();
            }
        }

        #endregion



        #region Method

        bool Validation()
        {
            for (int i = 0; i < gridView1.DataRowCount; i++)
            {
                int iRow = i;

                int quantity = Convert.ToInt32(gridView1.GetRowCellValue(iRow, colQuantity));
                int quantityStock = Convert.ToInt32(gridView1.GetRowCellValue(iRow, colQuanityStock));
                int quantityAdd = Convert.ToInt32(gridView1.GetRowCellValue(iRow, colQuantityAdd));

                if (quantityAdd <= 0)
                {
                    gridView1.FocusedRowHandle = i;
                    gridView1.SetColumnError(colQuantityAdd, string.Format("Bạn chưa nhập số lượng mua thêm."));
                    return false;
                }

                if (quantityStock < quantity)
                {
                    gridView1.FocusedRowHandle = i;
                    gridView1.SetColumnError(colQuantity, string.Format("Không đủ số lượng trong kho."));
                    return false;
                }
            }
            dxErrorProvider1.ClearErrors();

            if (txtCash.EditValue == null || txtCash.EditValue.ToString() == "0")
            {
                dxErrorProvider1.SetError(txtCash, "Vui lòng nhập");
                return false;
            }
            return true;
        }

        #endregion


        class tempOrderDetails
        {

            public orders_details OrdersDetails
            {
                get;
                set;
            }

            public int QuantityStock
            {
                get;
                set;
            }
            public int QuantityAdd
            {
                get;
                set;
            }
        }










    }
}